package cn.zyx.config.websocket;

import cn.zyx.common.properites.GlobalProperties;
import cn.zyx.common.utils.sys.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 自定义websocket拦截器
 */
public class SystemInfoSocketHandshakeInterceptor implements HandshakeInterceptor {

    private static Logger logger = LoggerFactory.getLogger(HandshakeInterceptor.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response
            , WebSocketHandler wsHandler
            , Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            //当参数是true时，当调用session这个方法时如果有原本的session则会返回原本的session，若没有则会新建一个session。
            //当参数是false时，当调用session时，原本有则会返回原本的session，若没有则不会新建一个session，而是返回null值
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            //String loginName1 = UserUtils.getUser().getLoginName();//获取当前用户登录名
            if (session != null) {
                // 使用loginName区分WebSocketHandler，以便定向发送消息
                String loginName = UserUtils.getUser().getLoginName();//获取当前用户登录名
                attributes.put(GlobalProperties.WEBSOCKET_LOGINNAME,loginName);
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
    }
}